package org.ualr.cpsc.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.amazon.s3shell.S3Store;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

public class DataStore {
    @SuppressWarnings("unchecked")
    public List<Photo> queryPhotos() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            String queryStr = String.format("select from %s where user_email==currentUser order by modification desc", Photo.class.getName());
            Query query = pm.newQuery(queryStr);
            query.declareParameters("String currentUser");
            List<Photo> photos = (List<Photo>) query.execute(getUserEmail());
            if (photos.size() == 0) {
                photos.size();
            }
            return photos;
        } finally {
            pm.close();
        }
    }
    
    public Photo readPhoto(Key key) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            return pm.getObjectById(Photo.class, key);
        } finally {
            pm.close();
        }
    }
    
    public Photo updatePhoto(Photo photo) {
        photo.setUserEmail(getUserEmail());
        photo.setUserId(getUserId());
        photo.setModificationDate(new Date());
        if (photo.getAdditionDate() == null) {
            photo.setAdditionDate(new Date());
        }
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            return pm.makePersistent(photo);
        } catch (RuntimeException re) {
            throw re;
        } finally {
            pm.close();
        }
    }
    
    public void deletePhoto(Photo photo) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.deletePersistent(photo);
        } finally {
            pm.close();
        }
    }
    
    public static String sluggifyTag(String tag) {
        return tag.toLowerCase().replaceAll("\\s+", "-").replaceAll("[^-a-z0-9]+","");
    }
    
    private static User getCurrentUser() {
        return UserServiceFactory.getUserService().getCurrentUser();
    }
    
    public static String getUserId() {
        User user = getCurrentUser();
        return user == null ? null : user.getUserId();
    }
    
    public static String getUserEmail() {
        User user = getCurrentUser();
        return user == null ? null : user.getEmail();
    }
    
    public static String storeFile(String id, String mimetype, final byte[] bytes) throws IOException {
        S3Store store = S3Store.getInstance();
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        headers.put("Content-Type", new ArrayList<String>());
        headers.get("Content-Type").add(mimetype);
        if (store.storeItem(id, bytes, ACLConstants.PUBLIC_READ, headers)) {
            return String.format("http://%s/%s/%s", store.getHost(), store.getBucket(), id);
        } else {
            return null;
        }
    }
}